package edu.thu.studio.ormdesigner.editor.action;

import org.eclipse.gef.commands.Command;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionFactory;

import edu.thu.studio.ormdesigner.editor.command.CreateTableCommand;
import edu.thu.studio.ormdesigner.editor.command.CreateViewNodeCommand;
import edu.thu.studio.ormdesigner.model.diagram.Diagram;
import edu.thu.studio.ormdesigner.model.diagram.node.Node;
import edu.thu.studio.ormdesigner.model.diagram.node.TableNode;
import edu.thu.studio.ormdesigner.model.diagram.node.ViewNode;
import edu.thu.studio.ormdesigner.model.orm.table.Table;
import edu.thu.studio.ormdesigner.model.orm.view.View;
import edu.thu.studio.ormdesigner.util.Properties;

public class PasteAction extends AbstractSelectionAction {
    
    public PasteAction(IWorkbenchPart part) {
        super(part);
        
        this.setId(ActionFactory.PASTE.getId());
        
    	this.setText(Properties.action_title_paste);
		ISharedImages sharedImages = PlatformUI.getWorkbench()
				.getSharedImages();
		setImageDescriptor(sharedImages
				.getImageDescriptor(ISharedImages.IMG_TOOL_PASTE));
		setDisabledImageDescriptor(sharedImages
				.getImageDescriptor(ISharedImages.IMG_TOOL_PASTE_DISABLED));
        
    }
    
    @Override
    protected boolean calculateEnabled() {
        return CopyManager.canPaste();
    }
    
    @Override
    public void run() {
        try {
            execute(createCommand());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private Command createCommand() {
        if (!calculateEnabled()) {
            return null;
        }
        
        Diagram diagram = this.getCurrentDiagram();
        Node node = CopyManager.paste();
        
        if (node instanceof ViewNode) {
            View view = CopyManager.pasteAsView();
            return new CreateViewNodeCommand(diagram, (ViewNode) node, view);
        } else {
            Table table = CopyManager.pasteAsTable();
            return new CreateTableCommand(diagram, (TableNode) node, table);
        }
        
    }
}
